<style lang="scss">
@import "../uv.scss";

</style>
<template>
  <div :class="taskType == 1 ? '' : 'pl30 pr30'">
    <div style="position: relative;z-index: 999;">
      <u-order-pop @success="successChange" @close="closeChange" :taskForm="taskForm" ref="orderPop"></u-order-pop>
    </div>
    <scroll-view :style="{height: mainHeight + 'px'}" scroll-anchoring :refresher-triggered="isRefreshing" :refresher-enabled="taskType == 1 ? false : true" scroll-y scroll-top="0" @refresherrestore="onRefresherRestore" @refresherrefresh="bindrefresherrefresh" @scrolltolower="onReachBottom" class="p1756538809">
      <div class="">
        <div class="common-empty" v-if="tableData.length === 0 && isOnce">
          <uv-empty mode="data" />
        </div>
        <div class="" v-for="(item, index) in tableData" :key="index">
          <u-item-delivery v-if="item.deliveryType == 1" :serviceStatus="item.service_status" :form="item">
            <template v-slot:time>
              <!-- <div class="fz30" style="font-weight: 500;color: #F39800;">{{item.desc}}</div> -->
              <div v-if="item.desc" class="fz30 fac" :style="{color: item.service_status == 4 || item.service_status ==  5 ? '#9fa0a0' : '#333'}">(
                <div class="fz30" :style="{color: item.service_status == 4 || item.service_status ==  5 ? '#9fa0a0' : '#F39800'}" style="font-weight: 500;">{{item.desc}}</div>)到达
              </div>
              <!-- <div v-if="item.service_status == 4" class="fz30 " style="color: #9FA0A0;">12.32送达</div>
            <div v-if="item.service_status == 5" class="fz30 " style="color: #9FA0A0;">16:48顾客取消</div> -->
            </template>
            <template v-slot:button style="width: 100%;">
              <div v-if="item.service_status == 0" class="p1756709756 fac jcc fz30" style="color: #9FA0A0;">
                <uv-count-down :key="item.id" :time="item.allocationTime" format="ss" autoStart millisecond></uv-count-down>
                <div style="color: #F39800 ">秒</div> 后自动拒绝
              </div>
              <div class="f" v-if="item.service_status == 0 || item.service_status == 1" style="width: 100%;">
                <div v-if="item.service_status == 0" class="p1756191456 pl30 pt30  fac jcc" style="width: 60%!important;">
                  <uv-button @click="acceptOrRejectTap(item, 2)" size="mini" text="">
                    <div class="fz36 p1756193077-1" style="color: #333;background-color: #fff!important;border:2rpx solid #C9CACA!important;">拒绝</div>
                  </uv-button>
                </div>
                <div v-if="item.service_status == 1 || item.service_status == 0" class="p1756191456 pl30 pr30 pt30 fac jcc" style="width: 100%;">
                  <uv-button @click="acceptOrRejectTap(item, 1)" size="mini" text="">
                    <div class="fz36 p1756193077-1" style="border:2rpx solid #E60012!important;color: #fff;">{{taskType ==
                    1 ? '收到' : '抢单'}}</div>
                  </uv-button>
                </div>
              </div>
              <div class="pl20 " style="box-sizing: border-box;width: 100%;" v-else-if="item.service_status != 1 && item.service_status != 4 && item.service_status != 5">
                <button v-if="item.is_report_location == 0 &&item.service_status == 2 && item.purchase_address_type != 2" @click="taskForm = item,this.$refs.orderPop.openFun('上报到位置')" class="common-button fz30 pl0 pr0 ml0 mr0  pt10 pb10" style="height:80rpx;width: 100%;color: #fff;background-color: #E60012;">上报到位置</button>
                <button v-if="(item.service_status == 3 &&item.type !=3) || (item.type == 3 && item.is_pay_advance_price == 1)" @click="taskForm = item,$refs.orderPop.openFun('送达')" class="common-button fz30  pl0 pr0 ml0 mr0 pt10 pb10" style="height:80rpx;width: 100%;color: #fff;background-color: #00AF53;">我已送达</button>
                <button v-if="item.service_status == 3 && item.type == 3 && item.is_pay_advance_price != 1" @click="taskForm = item,$refs.orderPop.openFun('发起支付')" class="common-button fz30 pl0 pr0 ml0 mr0 pt10 pb10" style="height:80rpx;width: 100%;color: #fff;background-color: #00AF53;">发起支付</button>
                <!-- || (item.purchase_address_type == 2 && item.is_report_location == 0 && item.type == 3) -->
                <button v-if="(item.service_status == 2 && item.is_report_location == 1 && item.type != 3 ) " @click="successChange({showType: '我已取货'})" class="common-button fz30 pl0 pr0 ml0 mr0  pt10 pb10" style="height:80rpx;width: 100%;color: #fff;background-color: #E60012;">我已取货</button>
                <button v-if="(item.is_report_location == 1 || (item.purchase_address_type == 2 && item.is_report_location == 0)) && item.service_status == 2 && item.type == 3" @click="taskForm = item,$refs.orderPop.openFun('我已购买')" class="common-button pl0 pr0 ml0 mr0 fz30  pt10 pb10" style="height:80rpx;width: 100%;color: #fff;background-color: #E60012;">我已购买</button>

              </div>

            </template>
          </u-item-delivery>
          <u-pet-care v-if="item.deliveryType == 2 && (item.service_status == 1 || item.service_status == 0)" :serviceStatus="item.service_status" :form="item">
            <template v-slot:time>
              <div v-if="item.desc" class="fz30 fac" :style="{color: item.service_status == 4 || item.service_status ==  5 ? '#9fa0a0' : '#333'}">(
                <div class="fz30" :style="{color: item.service_status == 4 || item.service_status ==  5 ? '#9fa0a0' : '#F39800'}" style="font-weight: 500;">{{item.desc}}</div>)到达
              </div>
            </template>
            <div class="" style="width: 100%;">
              <div v-if="item.service_status == 0" class="p1756709756 fac jcc fz30" style="color: #9FA0A0;">
                <uv-count-down :key="item.id" :time="item.allocationTime" format="ss" autoStart millisecond></uv-count-down>
                <div style="color: #F39800 ">秒</div> 后自动拒绝
              </div>
              <div class="f pl30 pr30 pt30 jcsb" style="justify-content: space-between!important;box-sizing: border-box;width: 100%;" v-if="item.service_status == 0">
                <button @click="acceptOrRejectTap(item, 2)" class="common-button pl0 pr0 ml0 mr0 fz36  " style="width: 40%;height:80rpx;color: #333;background-color: #fff;">拒绝</button>
                <button @click="acceptOrRejectTap(item, 1)" class="common-button pr0 pl0 ml0 mr0 fz36  " style="width: 55%;height:80rpx;color: #fff;background-color: #E60012;">收到</button>
              </div>
              <div v-if="item.service_status == 1" class="p30">
                <button @click="acceptOrRejectTap(item, 1)" class="common-button pr0 pl0 ml0 mr0 fz36 " style="width: 100%;height:80rpx;color: #fff;background-color: #E60012;">抢单</button>
              </div>
            </div>
          </u-pet-care>
          <u-pet-care-order v-if="item.deliveryType == 2 && (item.service_status != 1 && item.service_status != 0)" :serviceStatus="item.service_status" :form="item">
            <template v-slot:time>
              <div v-if="item.desc" class="fz30 fac" :style="{color: item.service_status == 4 || item.service_status ==  5 ? '#9fa0a0' : '#333'}">(
                <div :style="{color: item.service_status == 4 || item.service_status ==  5 ? '#9fa0a0' : '#F39800'}" class="fz30" style="font-weight: 500;">{{item.desc}}</div>)到达
              </div>
            </template>
            <template v-slot:button>
              <div class="pl20 " style="width: 100%;">
                <button v-if="item.is_report_location == 0 && item.service_status == 2" @click="taskForm = item,$refs.orderPop.openFun('上报到位置')" class="common-button pl0 pr0 ml0 mr0 fz36  pt10 pb10" style="height:80rpx;width: 100%;color: #fff;background-color: #E60012;">上报到位置</button>
                <button v-if="item.service_status == 2 && item.is_report_location == 1 && item.type != 3" @click="taskForm = item,$refs.orderPop.openFun('开始服务')" class="common-button pl0 pr0 ml0 mr0 fz36  pt10 pb10" style="height:80rpx;width: 100%;color: #fff;background-color: #E60012;">开始服务</button>
                <button v-if="item.service_status == 3" @click="taskForm = item,$refs.orderPop.openFun('我已完成')" class="common-button fz36  pl0 pr0 ml0 mr0 pt10 pb10" style="height:80rpx;width: 100%;color: #fff;background-color: #00AF53;">我已完成</button>
              </div>

            </template>
          </u-pet-care-order>
        </div>
      </div>
    </scroll-view>
  </div>
</template>

<script>
import petCareVue from './petCare.vue'
import petCareOrderVue from './petCareOrder.vue'
import itemDeliveryVue from './itemDelivery.vue'
import orderPopVue from '../components/orderPop.vue'
import payMixin from '../mixin/payMixin.js'
import commonMixin from '../mixin/common.js'
import { getOrderList, toDoOrderList, acceptOrReject } from '@/api/neighbor.js'
export default {
  components: {
    'u-order-pop': orderPopVue,
    'u-pet-care-order': petCareOrderVue,
    'u-pet-care': petCareVue,
    'u-item-delivery': itemDeliveryVue,
  },
  props: {
    taskType: {
      type: Number,
      default: 0
    },
        mainHeight: {
      type: Number,
      default: 0
    },
    userStatus: {
      type: Boolean,
      default: false
    }
  },
  mixins: [payMixin, commonMixin],
  data() {
    // 1=新任务，2=待取货/待服务，3=服务中，4=已完成，5=已取消
    return {
      tableData: [],
      taskForm: {},
      info: uni.getSystemInfoSync(),
      isOnce: false,
      isRefreshing: false, // 防止重复刷新
      total: 0,
      current_page: 0,
      taskStatus: 1,
      form: {
        page: 1,
        limit: 10,
        service_status: 0
      },
    }
  },
  methods: {
    closeChange() {
      this._clearAll()
      this.initPage(this.form.service_status)
    },
    successChange(value) {
      let { showType } = value
      if (showType == '开始服务' || showType == '我已取货') {
        this.startServiceTap(this.taskForm.id, res => {
          this._clearAll()
          this.initPage(this.form.service_status)
        })
        return
      }
      if (showType == '我已购买') {
        if (value.fileList && value.advance_payment_price) {
          this.havePurchasedTap({ order_id: this.taskForm.id, advance_payment_price: value.advance_payment_price, advance_payment_images: value.fileList }, () => {
            this.$refs.orderPop.closeTap()
            this._clearAll()
            this.initPage(this.form.service_status)
          })
        }
        return
      }
      if (showType == '发起支付') {
        this.$refs.orderPop.closeTap()
        this.initiationOfPaymentsTap({ order_id: this.taskForm.id, advance_payment_images: value.fileList, advance_payment_price: value.advance_payment_price }, () => {
          this._initPage()
        })
        return
      }
      if (showType == '上报到位置') {
        this.reportLocationTap(this.taskForm.id, () => {
          this.$refs.orderPop.closeTap()
          this._clearAll()
          this.initPage(this.form.service_status)
        })
        return
      }
      if (showType == '我已送达' || showType == '我已完成') {
        this.haveDeliveredTap({ order_id: this.taskForm.id, type: this.taskForm.type, images: value.fileList }, () => {
          this.$refs.orderPop.closeTap()
          this._clearAll()
          this.initPage(this.form.service_status)
        })
        return
      }


    },
    acceptOrRejectTap(item, status) {
      if (!this.userStatus) return uni.$uv.toast('请先打开上线接单开关')
      this.taskStatus = status
      if (this.taskType == 1) {
        uni.showLoading({ title: '请求中', mask: true })
        acceptOrReject({ order_id: item.id, status: status }).then(res => {
          if (res.code === 200) {
            uni.hideLoading()
            this._toDoOrderList()
          }
        }).catch(() => {
          uni.hideLoading()
        })
      } else {
        this.grabOrdersTap(item.id, res => {
          if (res) {
            this._clearAll()
            this.initPage(this.form.service_status)
          }
        })
      }

    },
    _clearAll() {
      this.tableData = []
      this.current_page = 0
      this.$set(this.form, 'page', 1)
    },
    addOrderTap(item) {
      uni.navigateTo({
        url: '/pages-neighbor/orderDesc?id=' + item.id
      });
    },
    onReachBottom() {
      if (this.total > this.tableData.length) {
        let page = this.form.page
        this.$set(this.form, 'page', page + 1)
        this.initPage(this.form.service_status)
      }
    },
    bindrefresherrefresh() {
      this._clearAll()
      this.isRefreshing = true
      this.initPage(this.form.service_status)

    },
    onRefresherRestore() {
      this.isRefreshing = false
    },
    payOrderFun() {
      this.$refs.popPwdRef.close();
      this._clearAll()
      this.initPage(this.form.service_status)
    },
    _toDoOrderList() {
      toDoOrderList({}).then(res => {
        if (res.code === 200) {
          if (res.result && res.result.length) {
            let data = res.result && res.result && JSON.parse(JSON.stringify(res.result)).map(item => {
              if (item.desc) item.desc = this.extractTime(item.desc)
              if (item.allocation_time) {
                item.allocationTime = (new Date(this.parseIosCompatibleDate(item.allocation_time)).getTime() + (1000 * 70)) - (new Date(this.parseIosCompatibleDate(item.allocation_time)).getTime())
              } else {
                item.allocationTime = 70000
              }
              item.deliveryType = item.type == 4 || item.type == 5 ? 2 : 1
              return this._initData(item)
            })
            this.tableData = data.length > 0 ? [data[0]] : []
          } else {
            this.$emit('taskTypeChange', this.taskStatus)
          }
        }
      }).catch(() => {
        uni.hideLoading()
      })
    },
    extractTime(str) {
      const regex = /\((.*?)\)/;
      const match = str.match(regex);
      return match ? match[1] : null;
    },
    initPage(service_status = 0, limit, cb = () => { }) {
      this.isOnce = false
      this.$set(this.form, 'service_status', service_status)
      if (this.form.page == this.current_page) return
      let form = JSON.parse(JSON.stringify(this.form))
      if (limit) form.limit = limit
      if (form.service_status != 0) {
        getOrderList(form).then(res => {
          this.isRefreshing = false
          this.isOnce = true
          if (res.code === 200) {
            let data = res.result && res.result.data && JSON.parse(JSON.stringify(res.result.data)).map(item => {
              if (item.desc) item.desc = this.extractTime(item.desc)
              if (item.type == 4 || item.type == 5) {
                item.deliveryType = 2
              } else {
                item.deliveryType = 1
              }
              return this._initData(item)
            })
            this.total = res.result.total
            this.current_page = res.result.current_page
            this.tableData = this.tableData.concat(data)
            cb(res)
          }
        }).catch(() => {
          this.isRefreshing = false
          this.isOnce = true
        })
      }
    },
    _initData(res) {
      let data = JSON.parse(JSON.stringify(res))
      let _d = {
        address: data.delivery_address_address,
        area: data.delivery_address_area,
        city: data.delivery_address_city,
        number: data.delivery_address_number,
        lat: (Number(data.delivery_address_lat) == 0 || Number(data.delivery_address_lat) == NaN) ? '' : data.delivery_address_lat,
        lng: (Number(data.delivery_address_lng) == 0 || Number(data.delivery_address_lng) == NaN) ? '' : data.delivery_address_lng,
        name: data.delivery_address_name,
        province: data.delivery_address_province,
        storey: data.delivery_address_storey,
        tel: data.delivery_address_tel,
        town: data.delivery_address_town
      }
      let _p = {
        address: data.pickup_address_address,
        area: data.pickup_address_area,
        city: data.pickup_address_city,
        number: data.pickup_address_number,
        lat: (Number(data.pickup_address_lat) == 0 || Number(data.pickup_address_lat) == NaN) ? '' : data.pickup_address_lat,
        lng: (Number(data.pickup_address_lng) == 0 || Number(data.pickup_address_lng) == NaN) ? '' : data.pickup_address_lng,
        name: data.pickup_address_name,
        province: data.pickup_address_province,
        storey: data.pickup_address_storey,
        tel: data.pickup_address_tel,
        town: data.pickup_address_town
      }
      let _pur = {
        storey: data.purchase_shop_title,
        address: data.purchase_shop_address,
        lat: (Number(data.purchase_shop_lat) == 0 || Number(data.purchase_shop_lat) == NaN) ? '' : data.purchase_shop_lat,
        lng: (Number(data.purchase_shop_lng) == 0 || Number(data.purchase_shop_lng) == NaN) ? '' : data.purchase_shop_lng,
      }
      data._d = _d
      data._p = _p
      data._pur = _pur
      return data
    }
  },

}
</script>
<style lang="scss" scoped>
@import "../common.scss";
.p1756538809 {
  box-sizing: border-box;
}

.p1756709756 {
  width: calc(100% - 60rpx);
  background: #fdf1dc;
  border-radius: 10rpx;
  padding-top: 10rpx;
  padding-bottom: 10rpx;
  margin-left: 30rpx;
  margin-right: 30rpx;
  box-sizing: border-box;
  text-align: center;
  margin-top: 30rpx;
}
</style>